import React, { useState, useEffect, useRef, useImperativeHandle } from 'react'
import './header.scss'
import { connect } from 'react-redux'
import { useHistory } from "react-router-dom";
import * as actionCreators from '@store/actionCreators'

export const Header = connect(
    state => ({
        main: state.main,
    }),
    dispatch => ({
        setActiveHeader: value => dispatch(actionCreators.setActiveHeader(value)),
        setHeaderHeight: value => dispatch(actionCreators.setHeaderHeight(value))
    }))(
        React.forwardRef((props, refP) => {

            let history = useHistory()

            useEffect(() => {
                const href = window.location.href.split('#')[1]
                if(href.includes('/ararin-ui/home')) {
                    props.setActiveHeader({type: 'left', index: 0})
                }else if(href.includes('/ararin-ui/view')) {
                    props.setActiveHeader({type: 'right', index: 0})
                }
            }, [window.location.href.split('#')[1]])

            const headerRef = useRef()

            useEffect(() => {
                props.setHeaderHeight(headerRef.current.offsetHeight || 0)
            }, [])

            const handleClick = (str, item, index) => {
                item.link && history.push(item.link)
                    props.setActiveHeader({type: str, index})
            }
    
            return  <div className="header" ref={headerRef}>
                        <h1 className="header_wrapper">
                            <div className="blur_bg_content">
                                <div className="bg_blur"></div>
                                <div className="mask"></div>
                                <div className="nav">
                                    <ul className="nav_left">
                                        {props.main.leftNav.map(
                                            (item, index) =>
                                                <li onClick={() => handleClick('left', item, index)} key={`nav_left${index}`} className={`nav_item ${item.active ? 'active' : ''}`}>{item.title}</li>
                                        )}
                                    </ul>
                                    <ul className="nav_right">
                                        {props.main.rightNav.map(
                                            (item, index) =>
                                                <li onClick={() => handleClick('right', item, index)} key={`nav_right${index}`} className={`nav_item ${item.active ? 'active' : ''}`}>{item.title}</li>
                                        )}
                                    </ul>
                                </div>
                            </div>
                            <div className="bg_content"></div>
                        </h1>
                    </div>
        })
)